package com.kgcx.coupon.service;

import com.kgcx.common.bean.ReturnData;
import com.kgcx.common.client.order.OrderClient;
import com.kgcx.common.client.order.pojo.UserMileage;
import com.kgcx.common.client.organization.CustomerClient;
import com.kgcx.common.client.organization.pojo.Customer;
import com.kgcx.common.redis.JsonRedisTemplate;
import com.kgcx.common.utils.CollectionUtils;
import com.kgcx.coupon.domain.*;
import com.kgcx.coupon.dto.MarketingPlanPushDto;
import com.kgcx.coupon.mapper.UserPullMapper;
import com.kgcx.coupon.vo.coupon.UserPlanVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author 何凯
 * @version 0.1
 * @description 营销方案推送
 * @time 2017/12/26 11:28
 * @since 0.1
 */
@Service
public class PlanPushService {
    @Autowired
    private UserPlanService userPlanService;
    @Autowired
    private UserCouponService userCouponService;
    @Autowired
    private CouponDetailService couponDetailService;
    @Autowired
    private CouponTypeService couponTypeService;
    @Autowired
    private JsonRedisTemplate<Long> numRedisTemplate;
    @Resource
    private CustomerClient customerClient;
    @Resource
    private OrderClient orderClient;
    @Resource
    private UserPullMapper userPullMapper; //老用户拉新次数

    private static final String COUPON_NUM = "user:coupon:num:";

    /**
     * 给用户绑定方案及优惠券
     *
     * @param userPlan
     */
    public void saveUserPlanAndCoupon(UserPlanVO userPlan) {
        if (null != userPlan) {
            //获取方案下面所有优惠券
            List<CouponDetail> details = couponDetailService.selectByPlanIds(userPlan.getPlanId());
            this.saveUserPlan(userPlan.getPlantList(), userPlan.getPlanId(), userPlan.getCreateId());
            this.saveUserCoupon(userPlan.getPlantList(), details, userPlan.getCreateId());
        }
    }

    /**
     * 保存用户方案
     *
     * @param plantList
     * @param planIds
     */
    public void saveUserPlan(List<UserPlan> plantList, List<Long> planIds, Integer createId) {
        List<UserPlan> newPlanList = new ArrayList<>();
        for (Long planId : planIds) {
            for (UserPlan userPlan : plantList) {
                userPlan.setPlanId(planId.intValue());
                userPlan.setCreateId(1);
                userPlan.setStatus(1);
                newPlanList.add(userPlan);
            }
        }
        userPlanService.insertByBatch(newPlanList);

    }

    /**
     * 保存用户优惠券
     *
     * @param plantList
     * @param detailList
     */
    public void saveUserCoupon(List<UserPlan> plantList, List<CouponDetail> detailList, Integer createId) {
        List<UserCoupon> couponList = new ArrayList<>();
        for (CouponDetail detail : detailList) {
            for (UserPlan userPlan : plantList) {
                UserCoupon userCoupon = this.setUserCoupon(detail, userPlan, createId);
                couponList.add(userCoupon);
            }
        }
        userCouponService.insertByBatch(couponList);
    }

    /**
     * 设置用户优惠券信息
     *
     * @param detail
     * @param userPlan
     * @return
     */
    public UserCoupon setUserCoupon(CouponDetail detail, UserPlan userPlan, Integer createId) {
        CouponType couponType = null;//couponTypeService.selectPrimaryKey(detail.getCouponId());
        StringBuilder sb = new StringBuilder(couponType.getNumbered());
        if ("1".equals(couponType.getCodeType())) {
            //根据时间生成
            sb.append(System.currentTimeMillis());
        } else if ("2".equals(couponType.getCodeType())) {
            //根据排序生成
            String key = COUPON_NUM + detail.getCouponId();
            Long num = numRedisTemplate.opsForValue().increment(key, couponType.getCumulativeNum());
            sb.append(num);
        }

        UserCoupon userCoupon = new UserCoupon();
        userCoupon.setCouponCode(sb.toString());
        userCoupon.setUserId(userPlan.getUserId());
        userCoupon.setUserName(userPlan.getUserName());
        userCoupon.setPhone(userPlan.getPhone());
        userCoupon.setCouponId(detail.getCouponId());
        userCoupon.setCreateId(createId);
        return userCoupon;
    }

    /**
     * 营销方案推送List页面接口
     *
     * @param pageNum
     * @param pageSize
     * @param userName
     * @param userPhone
     * @param regStartDate
     * @param regEndDate
     * @return
     */
    public ReturnData<?> getList(Integer pageNum, Integer pageSize, String userName, String userPhone,
                                 Long regStartDate, Long regEndDate) {
        HashMap<Long, UserMileage> userMap = new HashMap<>();
        List<MarketingPlanPushDto> returnList = new ArrayList<>();
        ReturnData<List<MarketingPlanPushDto>> returnDa = ReturnData.getResult();
        List<Customer> list = customerClient.queryCustomerList(pageNum, pageSize, null, null, userName, userPhone, null, regStartDate, regEndDate);
        if (CollectionUtils.isNotEmpty(list)) {
            List<Long> userIds = new ArrayList<>();
            //循环得到用户ID
            for (Customer customer : list) {
                userIds.add(customer.getKid());
            }
            // 获取到用户里程
            userMap = orderClient.queryUserMileage(userIds);
            if (null == userMap) {
                userMap = new HashMap<>();
            }
            for (Customer customerDto : list) {
                MarketingPlanPushDto marketingPlanPushDto = new MarketingPlanPushDto();
                marketingPlanPushDto.setUserName(customerDto.getName());
                //拉新数
                UserPull userPull = userPullMapper.selectByPrimaryKey(customerDto.getKid());
                if (null != userPull) {
                    marketingPlanPushDto.setNewNumber(userPull.getPullQty());
                } else {
                    marketingPlanPushDto.setNewNumber(0);
                }
                marketingPlanPushDto.setRegDate(customerDto.getCreateTime());
                marketingPlanPushDto.setState(customerDto.getStatus());
                marketingPlanPushDto.setUserPhone(marketingPlanPushDto.getUserPhone());
                marketingPlanPushDto.setUserId(customerDto.getKid());
                UserMileage userMileage = userMap.get(customerDto.getKid());
                if (null == userMileage) {
                    //当月里程(km)
                    marketingPlanPushDto.setMonthlyMileage(0);
                    //总里程(km)
                    marketingPlanPushDto.setTotalMileage(0);
                } else {
                    //当月里程(km)
                    marketingPlanPushDto.setMonthlyMileage(userMileage.getMonthly() == null ? 0 : userMileage.getMonthly());
                    //总里程(km)
                    marketingPlanPushDto.setTotalMileage(userMileage.getTotal() == null ? 0 : userMileage.getTotal());
                }
                returnList.add(marketingPlanPushDto);
            }
        }
        returnDa.setData(returnList);
        return returnDa;
    }
}
